package com.example.springbootelsatic.service.impl;

import com.example.springbootelsatic.model.Person;
import com.example.springbootelsatic.repository.PersonRepository;
import com.example.springbootelsatic.service.PersonService;
import lombok.extern.slf4j.Slf4j;

import org.elasticsearch.common.io.stream.NamedWriteable;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class PersonServiceImpl implements PersonService {
    @Autowired
    private PersonRepository personRepository;
//    private static final Logger log = LoggerFactory.getLogger(PersonServiceImpl.class);

    /**
     * 用户添加功能
     *
     * @param person
     * @return
     */
    @Override
    public Person save(Person person) {
        try {
            Person save = personRepository.save(person);
            log.info("用户添加" + save.toString());
            return save;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("在添加用户信息时报错");
            return null;
        }
    }

    /**
     * 批量添加
     *
     * @param personList
     * @return
     */
    @Override
    public Iterable<Person> saveAll(List<Person> personList) {
        try {
            Iterable<Person> people = personRepository.saveAll(personList);
            for (Person person : people) {
                log.info("用户添加:" + person.toString());
            }
            return people;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("批量添加用户信息时报错");
            return null;
        }
    }

    /**
     * 自定义查询，根据年龄范围查询
     */
    @Override
    public Iterable<Person> findByAgeBetween(int i, int i1) {
        try {
            List<Person> people = personRepository.findByAgeBetween(i, i1);

            for (Person person : people) {
                log.info("用户查询:" + person.toString());
            }
            return people;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询报错");
            return null;
        }
    }

    /**
     * 删除
     */
    @Override
    public String deleteById(int id) {
        try {
            personRepository.deleteById(2l);

            return "删除成功";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询报错");
            return null;
        }
    }

    /**
     * 更新
     */
    @Override
    public boolean update(Person person1) {
        try {
            personRepository.findById(person1.getId()).ifPresent(person -> {
                person.setRemark(person.getRemark() + "\n更新更新更新更新更新");
                person.setName("王聪聪");
                Person save = personRepository.save(person);
                log.info("【save】= {}", save);
            });
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    //构造高级查询
    @Override
    public List<Person> customAdvanceSelect(String name) {

        // 构造查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本的分词条件
        queryBuilder.withQuery(QueryBuilders.matchQuery("remark", "东汉"));
        // 排序条件
        queryBuilder.withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC));
        // 分页条件
        queryBuilder.withPageable(PageRequest.of(0, 2));
        Page<Person> people = personRepository.search(queryBuilder.build());
        log.info("【people】总条数 = {}", people.getTotalElements());
        log.info("【people】总页数 = {}", people.getTotalPages());
        people.forEach(person -> log.info("【person】= {}，年龄 = {}", person.getName(), person.getAge()));
        return null;
    }
    //按年龄倒叙
    @Override
    public void select1() {
        personRepository.findAll(Sort.by(Sort.Direction.DESC, "birthday"))
                .forEach(person -> log.info("{} 生日: {}", person.getName() + person.getBirthday()));
    }



}





